package com.link.base.base.product.controller;

import com.link.base.base.product.model.PartsCostTemp;
import com.link.base.base.product.service.PartsCostTempService;
import com.link.base.user.model.CoreUser;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.CallParam;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.cllog.LCLogger;
import com.link.core.util.RedisUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 成本信息汇总临时对象
 *
 * @date 2023-08-15 09:04:14
 */
@Controller
@RequestMapping("/link/partsCostTemp")
public class PartsCostTempController extends BasicController<PartsCostTemp> {

    @Resource
    private KeyGenerateService keyGenerateService;

    @Resource
    private PartsCostTempService partsCostTempService;

    @Override
    public BasicService<PartsCostTemp> getBasicService() throws Exception {
        return partsCostTempService;
    }

    public void beforQueryAllOrExample(PartsCostTemp entity,
                                       HttpServletRequest request) throws Exception {



    }


    public void beforInsert(PartsCostTemp entity,
                            HttpServletRequest request) throws Exception {
        if (null != entity) {
            entity.setCheckStatus("New");
            entity.setImportStatus("New");
        }
    }

    public void beforUpsert(PartsCostTemp entity,
                            HttpServletRequest request) throws Exception {
        if (null != entity) {
            String wlmc = entity.getWlmc();
            if (!StringUtils.isNull(wlmc)) {
                String[] arr = wlmc.split("-");
                int len = arr.length;
                if (len == 2) {
                    entity.setWlmcHead(arr[0]);
                    entity.setWlmcTail(arr[1]);
                }
                if (len == 1) {
                    entity.setWlmcHead(arr[0]);
                    entity.setWlmcTail(null);
                }
            }
        }
    }

    @RequestMapping({"/dataCheck"})
    @ResponseBody
    public Map<String, Object> dataCheck(@JsonParam PartsCostTemp entity,
                                         QueryParams qps,
                                         HttpSession session,
                                         HttpServletRequest request,
                                         HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        CoreUser user = UserUtil.getUser();
        if (null == user || null == user.getId()) {
            throw new RuntimeException("登录信息异常!");
        }
        LinkRedisClient jedis = null;
        String validateRedisKey = "PARTS_COST_CHECK" + user.getId();
        try {
            jedis = RedisUtil.getJedis();
            boolean isRedisExist = jedis.exists(validateRedisKey);
            if (isRedisExist) {
                result.put("success", false);
                result.put("result", "数据正在校验中，请勿重复校验!!!");
                return result;
            } else {
                // 设置失效时间为 10s，防止重复刷新
                jedis.set(validateRedisKey, "1");
                jedis.expire(validateRedisKey, 15);
            }

            entity.setCreatedBy(user.getId());
            //进行校验校验
            String checkMsg = partsCostTempService.runDataCheck(entity);

            // 还原锁
            jedis.del(validateRedisKey);

            result.put("success", true);
            result.put("result", checkMsg);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        } finally {
            RedisUtil.returnResource(jedis);
        }
        return result;
    }


    @RequestMapping({"/dataImport"})
    @ResponseBody
    public Map<String, Object> dataImport(@JsonParam PartsCostTemp entity,
                                          QueryParams qps,
                                          HttpSession session,
                                          HttpServletRequest request,
                                          HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            CoreUser user = UserUtil.getUser();
            if (null == user || null == user.getId()) {
                throw new RuntimeException("登录信息异常!");
            }
            LinkRedisClient jedis = RedisUtil.getJedis();
            String importKey = "PARTS_COST_IMPORT" + user.getId();
            if (jedis.exists(importKey)) {
                throw new RuntimeException("数据导入中，请稍后!");
            }


            entity.setCreatedBy(user.getId());
            CallParam callParam = partsCostTempService.runDataImport(entity);

            // 还原锁
            jedis.del(importKey);

            result.put("success", true);
            result.put("result", callParam.getMsgData());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping({"/addExcelData"})
    @ResponseBody
    public Map<String, Object> addExcelData(@JsonParam PartsCostTemp entity,
                                            QueryParams qps,
                                            HttpSession session,
                                            HttpServletRequest request,
                                            HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            if (null == entity.getAttachmentId()) {
                throw new Exception("上传文件数据丢失!");
            }
            partsCostTempService.insertExcelData(entity.getAttachmentId());
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping({"/batchDeleteData"})
    @ResponseBody
    public Map<String, Object> batchDeleteData(@RequestBody List<PartsCostTemp> partsCostTempList,
                                               QueryParams qps,
                                               HttpSession session,
                                               HttpServletRequest request,
                                               HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            for (PartsCostTemp partsCostTemp : partsCostTempList) {
                partsCostTempService.deleteById(partsCostTemp);
            }
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping({"/deleteAll"})
    @ResponseBody
    public Map<String, Object> deleteAll(@JsonParam PartsCostTemp entity,
                                         HttpSession session,
                                         HttpServletRequest request,
                                         HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            if (null == entity.getProjectId()) {
                throw new RuntimeException("项目Id不能为空!");
            }
            partsCostTempService.deleteAll(entity);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }
}
